const Subscription = require('egg').Subscription;
const moment = require('moment');
const AipOcrClient = require("baidu-aip-sdk").ocr;
// 设置APPID/AK/SK
var APP_ID = "120562836";
var API_KEY = "Ahk1zbfrpLainhlodddq7w73";
var SECRET_KEY = "O3mCzNtctn0QoEwL7f0Lvrp0mSrbQRid";
//用于获取图片的高度
const { imageSize } = require('image-size');

const { createData, createData2, createDataNew } = require('../utils/tools')


class Task extends Subscription{
    static get schedule(){
        return {
            interval: '5s',
            type: 'worker',
            immediate: true,
            // disable: true
        }
    }


    async subscribe(){
        let { ctx } = this;

        //搜索待执行的任务
        let Task = await ctx.model.Task.findOne({
            where: { status: 0 },
            order: [['createdAt','ASC']]
        })

        if(!Task){
            return;
        }
        let { id, url, type } = Task.dataValues;

        // 修改这个执行状态为执行中
        await ctx.model.Task.update({status:1 }, {
            where: { id }
        })
        let that = this;
        try{
            //走百度云
            var fs = require('fs');
            var image = fs.readFileSync(this.config.static.dir+'/'+url);
            let dimensions = imageSize(image)
            let width = dimensions.width/2;
            // 新建一个对象，建议只保存一个对象调用服务接口
            var client = new AipOcrClient(APP_ID, API_KEY, SECRET_KEY);
       
            // 调用通用文字识别(含位置高精度版）
            client.accurate(image.toString("base64")).then(function(result) {
                let data = result.words_result.filter(item=>item.words.indexOf('元')>-1&&(item.location.left>width||item.location.width>width)).map(item=>{
                    if(item.words.length!=5&&item.words[1]!='.'){
                        //针对.没有识别出来的数字，要在第二位加上点
                        item.words = item.words.slice(0,1) + '.' + item.words.slice(1)
                    }
                    return item.words;
                }).reverse().join(' ')
                let z_name = '';
                // 前两种玩法，是取第一位为庄
                let z_point = result.words_result.filter(item=>item.words.indexOf('元')>-1&&(item.location.left>width||item.location.width>width))[0]
                let z_top = z_point.location.top;
                let name_item = result.words_result.filter(item=>item.location.top>(z_top-8)&&item.location.top<(z_top+8)).filter(item=>item.words.indexOf('元')==-1)
                if(name_item.length>0){
                    z_name = name_item[0].words;
                }
                if(type==1){
                    createData(data, id, that, z_name)
                }else if(type==2){
                    createData2(data, id, that, z_name)
                }else if(type==3){
                     // 1. 找到红包的名字
                    let name = result.words_result.filter(item=>item.words.indexOf('的红包')>-1)[0].words.split('的红包')[0];
                    let name_point = result.words_result.filter(item=>item.words.indexOf('的红包')>-1)[0].location.top;
                    if(name==""){
                        //在没有值的时候，要寻找同高度的文字做拼接, 但是Left要小于宽度的一半  width
                        result.words_result.filter(item=>item.location.top>(name_point-8)&&item.location.top<(name_point+8)&&item.location.left<width).forEach(item=>{
                            name = name + item.words
                        })
                    }
                    // 根据名字找到庄金额的位置
                    let point_top = result.words_result.filter(item=>item.words.indexOf(name)>-1)
                    if(point_top.length==2){
                        point_top = point_top[1].location.top;
                    }else{
                        point_top= false
                    }
                    
                    let z_index; //找到庄的坐标 
                    let data = result.words_result.filter(item=>item.words.indexOf('元')>-1&&(item.location.left>width||item.location.width>width)).map((item, index)=>{
                        if(item.words.length!=5&&item.words[1]!='.'){
                            //针对.没有识别出来的数字，要在第二位加上点
                            item.words = item.words.slice(0,1) + '.' + item.words.slice(1)
                        }
                        // 设置5像素的误差,找到庄的坐标
                        if(point_top){
                            if((item.location.top>point_top-5)&&(item.location.top<point_top+5)){
                                z_index = index;
                            }
                        }
                        return item.words;
                    })
                    if(z_index>=0){
                        // 先移除庄位，在插入到第一条
                        let moveElement = data.splice(z_index, 1)[0]
                        data.unshift(moveElement)
                    }
                    
                    data = data.reverse().join(' ')
                    createDataNew(data, id, that, name)
                }
            
            }).catch(async function(err) {
                // 修改这个执行状态为执行中
                await ctx.model.Task.update({status: 3 }, {
                    where: { id }
                })
                // 如果发生网络错误
                console.log(err);
            });
        }catch(e){
            // 修改这个执行状态为执行中
            await ctx.model.Task.update({status: 3 }, {
                where: { id }
            })
            console.log(e);
        }

    }
}

module.exports = Task